#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/wait.h>

void run_shell()
{
    char command[1024];
    char* args[64];
    
    while(1)
    {
        char cwd[1024];
        if(getcwd(cwd, sizeof(cwd)) != NULL)
        {
            printf("[%s] myshell> ", cwd);
        }
        else
        {
            perror("getcwd failed");
            printf("myshell> ");
        }

        if(fgets(command, sizeof(command), stdin) == NULL)
            continue;

        if(command[strlen(command) - 1] == '\n')
        {
            command[strlen(command) - 1] = '\0';
        }

        if(strcmp(command, "exit") == 0) break;

        char* redirect_pos = strchr(command, '>');
        char filename[128] = {0};

        if (redirect_pos)
        {
            *redirect_pos = '\0'; // 断开命令和重定向部分
            redirect_pos++;
            while (*redirect_pos == ' ') redirect_pos++; // 跳过空格
            strncpy(filename, redirect_pos, sizeof(filename) - 1);
        }

         // 分割命令为参数
        int i = 0;
        char* token = strtok(command, " ");
        while (token != NULL)
        {
            args[i++] = token;
            token = strtok(NULL, " ");
        }
        args[i] = NULL;

        // 添加 cd 命令处理（必须在主进程执行）
        if(args[0] != NULL && strcmp(args[0], "cd") == 0)
        {
            if(args[1] == NULL && strcmp(args[0], "cd") == 0)
            {
                fprintf(stderr, "cd: missing operand\n");
            }
            else
            {
                if (chdir(args[1]) != 0)
                {
                    perror("cd failed");
                }
            }
            continue; // 不再 fork
        }

        // fork 子进程执行其他命令
        pid_t pid = fork();
        if (pid == 0)
        {
            if (filename[0] != '\0')
            {
                int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0644);
                if (fd < 0)
                {
                    perror("open failed");
                    exit(1);
                }
                dup2(fd, STDOUT_FILENO);
                close(fd);
            }

            execvp(args[0], args);
            perror("exec failed");
            exit(1);
        }
        else if (pid > 0)
        {
            wait(NULL);
        }
        else
        {
            perror("fork failed");
        }
     }
}
